package yaowen.com.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private GridView gridView;
    private List<Map<String,Object>> data_list;
    private SimpleAdapter sim_adapter;
    //图片封装为一个组
    private int[] icon={R.drawable.camera,R.drawable.calendar,R.drawable.chrome,R.drawable.email,R.drawable.maps,R.drawable.music,
            R.drawable.notes,R.drawable.recorder,R.drawable.phone,R.drawable.playstore,R.drawable.gallery,R.drawable.twitter};//R.drawable.calculator};
    private String[] iconName={"照相机","日历","浏览器","邮箱","地图","音乐","便签","录音","电话","应用商店","图库","迅雷"};//,"计算器"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView= (GridView) findViewById(R.id.gridView);
        //新建List
        data_list=new ArrayList<Map<String, Object>>();
        //获取数据
        getData();
        //新建数据
        String[] from={"image","text"};
        int[] to={R.id.img,R.id.tv};
        sim_adapter=new SimpleAdapter(this,data_list,R.layout.grid_item,from,to);
        //配置适配器
        gridView.setAdapter(sim_adapter);
        //当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //在本例中arg2=arg3
                HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
                //显示所选Item的ItemText
                 String textTest=(String)item.get("text");
                 setTitle(textTest);
                 Toast.makeText(getApplicationContext(), "你点击的是：" + textTest, Toast.LENGTH_SHORT).show();
            }
        });
    }
    private List<Map<String,Object>> getData() {
        //icon和iconName的长度是相同的，这里任选其一都可以
        for (int i=0;i<icon.length;i++){
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("image",icon[i]);
            map.put("text",iconName[i]);
            data_list.add(map);
        }
        return data_list;
    }
}
